package com.woniuxy.core.service.impl;

import  com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.core.mapper.RelArticleTypeMapper;
import com.woniuxy.core.service.AllArticleService;
import com.woniuxy.core.mapper.AllArticleMapper;
import com.woniuxy.entity.AllArticle;
import com.woniuxy.entity.DTO.ArticleUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author nanqiao
* @description 针对表【all_article(内容主表（帖子）)】的数据库操作Service实现
* @createDate 2025-07-10 15:30:19
*/
@Service
public class AllArticleServiceImpl extends ServiceImpl<AllArticleMapper, AllArticle>
    implements AllArticleService{
    @Autowired
    private AllArticleMapper allArticleMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RelArticleTypeMapper relArticleTypeMapper;
    @Override
    public List<ArticleUserDTO> selectArticlesByTypeId(Integer typeId) {
        return allArticleMapper.selectArticlesWithUsersByTypeId(typeId);
    }
    @Override
    public boolean removeById(Long id) {
        // 删除关联表中的数据
        relArticleTypeMapper.deleteByArticleId(id);
        // 删除主表数据
        return super.removeById(id);
    }
    @Override
    public List<AllArticle> searchArticlesByTitle(String title) {
        return allArticleMapper.selectByTitleLike(title);
    }

    @Override
    public Long getAuthorIdByArticleId(Long articleId) {
        return allArticleMapper.selectUserIdByArticleId(articleId);
    }
    @Override
    public List<AllArticle> getArticlesByUserId(Long userId) {
        return allArticleMapper.selectByUserId(userId);
    }
    @Override
    public void incrementViewCount(Long articleId) {
        String key = "article:viewCount";
        // 增加 Redis 中的浏览量
        Double score = redisTemplate.opsForZSet().incrementScore(key, articleId, 1);

        // 同时更新数据库中的浏览量（可选，根据业务需求决定是否实时同步）
        AllArticle article = getById(articleId);
        if (article != null) {
            article.setViewCount(score.longValue());
            updateById(article);
        }
    }


    @Override
    public List<AllArticle> getAllArticlesByViewCount() {
        String key = "article:viewCount";

        Set<ZSetOperations.TypedTuple<Object>> tuples =
                redisTemplate.opsForZSet().reverseRangeWithScores(key, 0, -1);

        List<Long> articleIds = new ArrayList<>();
        Map<Long, Long> viewCountMap = new HashMap<>();

        if (tuples != null) {
            for (ZSetOperations.TypedTuple<Object> tuple : tuples) {
                Object value = tuple.getValue();
                Long articleId;
                if (value instanceof String) {
                    articleId = Long.valueOf((String) value);
                } else if (value instanceof Number) {
                    articleId = ((Number) value).longValue();
                } else {
                    continue;
                }
                articleIds.add(articleId);
                viewCountMap.put(articleId, tuple.getScore().longValue());
            }
        }
        if (articleIds.isEmpty()) {
            return Collections.emptyList();
        }
        List<AllArticle> articles = allArticleMapper.selectWithLikeCountByIds(articleIds);
        for (AllArticle article : articles) {
            article.setViewCount(viewCountMap.getOrDefault(article.getId(), 0L));
        }
        return articles;
    }

    @Override
    public AllArticle getArticleWithLikeCountById(Long id) {
        return allArticleMapper.selectWithLikeCountById(id);
    }

}




